package com.itheima.tools;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 单本书记下载的工具类
 */
public class OneBook {
    public static void downOneBook(String FristUrl) throws Exception {
        //确定小说第一张的url
        String url = FristUrl;
        while (true) {

            //创建httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置请求方式
            HttpGet httpGet = new HttpGet(url);
            //设置请求参数
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");
            //发送请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            //获取数据
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
//        System.out.println(html);
            //处理br标签
            html.replaceAll("&lt;br/&gt;", "/n");
            //解析数据
            Document document = Jsoup.parse(html);
            //获取章节名称
            Elements elements1 = document.select("#wrapper > div.content_read > div > div.con_top > a:nth-child(4)");
            System.out.println(elements1);
            String name = elements1.text();
            String book = "";
            //解析章节数据
            Elements elements = document.select("#content");
            for (Element element : elements) {
//                System.out.println(element.text());
                book = element.text();
            }
            IOTest.mywrite(name, book);

            //获取下一章数据
            Elements next = document.select("#wrapper > div.content_read > div > div.bottem2 > a:nth-child(4)");
            String href = next.attr("href");
            System.out.println(href);
            if (href.length() < 10) {
                break;
            }
            //当href正常的时候,就传给之前的
            url = "http://www.xbiquge.la"+href;

            //4. 关闭httpClient对象
            httpClient.close();

        }
    }
}
